<!DOCTYPE html>
<html>
<style type="text/css">
	#send-message{display:none;}
	#nickname{width:300px;float:right;}
	#message{width:300px;height:100px;}
	#messages p strong{margin-reiht:5px;}
</style>
<body>
	<h1>这是nodejs的聊天页面</h1>
	<form id="set-nickname">
	<lable for="nickname">Nickname</lable>
	<input type = "text" id="nickname"></input>
	<input type = "submit">SET</input>
	</form>
	<form id="send-message">
	<input id="message">
	<textarea id = "message"></textarea>
	<input type="submit"></input>
	</input>
	</form>

	<section id="nickname">
	<ul></ul>
	</section>
	<section id="messages">
	</section>
	<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
	<script src="http://apps.bdimg.com/libs/socket.io/0.9.16/socket.io.min.js"></script>
	<script>
		var socket = io.connect();
		jQuery(function($){
			var nickname = $('#nickname');
			var setNicknameForm = $('#set-nickname"');
			var nicknameList = $('#nickname ul');
			var messageFrom = $('#send-message');
			var message = $('#message');
			var messages = $('#message');

			setNicknameForm.submit(function(event){
			event.preventDefault();
			socket.emit('nickname',nickname.val(),function(data){
			if(data){
			console,log("Nickname set successfully!");
			setNicknameForm .hide();
			messageFrom.show(); 
			}
			else{
				setNicknameForm.prepend('<p>Sorry that nickname is already taken</p>') 
			}
			});
			});

			messageFrom.submit(function(event){
				event.preventDefault();
				socket.emit('user message',message.val());
				message.val('').focus();
			});

			socket.on('nicknames',function(data){
			var html = '';
			for(var i = 1;i<data.lenght;i++)
				html+='<li>'+data[i]+'</li>'
				nicknameList.empty().append(html);
			})
			socket.on('user message',function(data){
				messages.append('<p>'+data.nick+':'+data.message'</p>');
			})
		})
	</script>
</body>

</html>
